//
//  CellView.swift
//  SearchHeader
//
//  Created by 万孟超 on 2023/10/12.
//

import Cocoa
import SnapKit

class CellView: NSTableCellView {
    
    var checkAction: ((Bool) -> ())?
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        // Drawing code here.
    }
    var title: String? {
        didSet {
            titleLabel.stringValue = title ?? ""
        }
    }
    
    var isSelect: Bool = false {
        didSet {
            if isSelect {
                checkButton.state = .on
            }else{
                checkButton.state = .off
            }
        }
    }
    
    lazy var checkButton: NSButton = {
       let bt = NSButton()
        bt.setButtonType(.switch)
        bt.title = ""
        bt.target = self
        bt.action = #selector(buttonClicked)
        return bt
    }()
    
    lazy var titleLabel: NSTextField = {
        let tf = NSTextField()
        tf.isVerticalCenter = true
        tf.font = .systemFont(ofSize: 14)
        tf.isBordered = false
        tf.isEditable = false
        tf.textColor = .black
        tf.bezelStyle = .roundedBezel
        return tf
    }()
    
    override init(frame frameRect: NSRect) {
        super.init(frame: .zero)
        installSubview()
    }
    
    func installSubview() {
        
        // 添加标题
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalToSuperview()
        }
        
        addSubview(checkButton)
        checkButton.snp.makeConstraints { make in
            make.right.equalTo(-30)
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc func buttonClicked() {
        if checkButton.state == .on {
            checkAction?(true)
        } else {
            checkAction?(false)
        }
    }
}
